<template>
  <div class="container">
    <a-row :gutter="16">
      <a-col :flex="1">
        <a-form :model="formModel" label-align="left">
          <a-row :gutter="16">
            <a-col flex="312px">
              <a-form-item field="name" label="成员姓名" label-col-flex="60px">
                <a-input v-model="formModel.name" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col flex="312px">
              <a-form-item
                field="accountState"
                label="账号状态"
                label-col-flex="60px"
              >
                <a-select
                  v-model="formModel.accountState"
                  :options="statusOptions"
                  placeholder="请选择"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-col>
      <a-col :flex="'128px'" style="text-align: right">
        <a-space :size="8">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button type="outline" @click="reset">清空</a-button>
        </a-space>
      </a-col>
    </a-row>
    <a-divider :margin="24" style="margin-top: 4px" />
    <a-row :gutter="16" style="margin-bottom: 16px">
      <a-col :flex="1">
        <table-title title="成员列表"></table-title>
      </a-col>
      <a-col :flex="'280px'" style="text-align: right">
        <div v-permission>
          <a-space :size="8">
            <a-button type="outline" @click="importDialogVisible = true"
              >导入成员</a-button
            >
            <a-button type="outline"
              ><a-link
                :href="`/api/cde-collaboration/project/exportUser?projectId=${projectId}`"
                >导出成员</a-link
              ></a-button
            >
            <a-button type="primary" @click="add">添加成员</a-button>
          </a-space>
        </div>
      </a-col>
    </a-row>
    <div class="table-box">
      <a-table
        row-key="id"
        :loading="loading"
        :scroll="{ y: '100%' }"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        table-layout-fixed
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #projectAdmin="{ record }">
          <span
            class="mini-dot"
            :style="{
              backgroundColor: record.projectAdmin ? '#33B737' : '#FF4D4F',
            }"
          ></span>
          <span>{{ record.projectAdmin ? '是' : '否' }}</span>
        </template>
        <template #accountState="{ record }">
          <a-tag v-if="record.accountState === 1" bordered color="blue"
            >正常</a-tag
          >
          <a-tag v-else-if="record.accountState === 2" bordered color="orange"
            >未激活</a-tag
          >
          <a-tag v-else bordered>已停用</a-tag>
        </template>
        <template #operations="{ record }">
          <a-button type="text" size="small" @click="detail(record)"
            >详情</a-button
          >
          <span v-permission>
            <a-button type="text" size="small" @click="update(record)"
              >编辑</a-button
            >
            <a-dropdown
              @select="(val) => handleSelect(val as string, record.id)"
            >
              <a-button type="text" size="small">...</a-button>
              <template #content>
                <a-doption class="danger-text" value="remove"
                  >移除项目</a-doption
                >
                <a-doption value="send">生成邀请链接</a-doption>
              </template>
            </a-dropdown>
          </span>
        </template>
      </a-table>
    </div>
    <AddMember
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :form="selectForm"
      :disabled="disabled"
      @refresh="search"
    />
    <UploadMembers
      v-if="importDialogVisible"
      v-model="importDialogVisible"
      @refresh="search"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRoute } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import useClipboard from 'vue-clipboard3';
  import {
    getMemberList,
    MemberListParams,
    MemberRecord,
    removeMember,
  } from '@/api/member';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import Modal from '@arco-design/web-vue/es/modal';
  import TableTitle from '@/components/table-title/index.vue';
  import { Message } from '@arco-design/web-vue';
  import AddMember from './add-member.vue';
  import UploadMembers from './upload-members.vue';
  import { memberColumns, Column } from './table-column';

  // 列表表格展示
  const generateFormModel = () => {
    const initData: MemberRecord = {
      name: undefined,
      accountState: undefined,
    };
    return initData;
  };
  const { loading, setLoading } = useLoading(true);
  const renderData = ref<MemberRecord[]>([]);
  const formModel = ref(generateFormModel());
  const columns = ref<Column[]>(memberColumns);
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showTotal: true,
    showMore: true,
    showJumper: true,
    showPageSize: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const statusOptions = ref<SelectOptionData[]>([
    {
      label: '正常',
      value: 1,
    },
    {
      label: '未激活',
      value: 0,
    },
    {
      label: '已停用',
      value: -1,
    },
  ]);

  // 列表数据相关
  const route = useRoute();
  const projectId = ref<string>((route.params?.projectId as string) || '');
  const fetchData = async (
    params: MemberListParams = { pageNo: 1, pageSize: 10 }
  ) => {
    setLoading(true);
    try {
      const { current, ...rest } = params;
      const apiParams = {
        ...rest,
        pageNo: current || 1,
        projectId: projectId.value,
      };
      const { data } = await getMemberList(apiParams);
      renderData.value = data.list || [];
      pagination.current = apiParams.pageNo;
      pagination.pageSize = apiParams.pageSize;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  const search = () => {
    // search时重新回到第一页
    const { pageSize } = pagination;
    fetchData({
      pageSize,
      current: 1,
      ...formModel.value,
    });
  };
  const reset = () => {
    formModel.value = generateFormModel();
    const { pageSize } = pagination;
    fetchData({ pageSize, current: 1 });
  };
  const onPageChange = (current: number) => {
    const { pageSize } = pagination;
    fetchData({ pageSize, current, ...formModel.value });
  };
  const onPageSizeChange = (pageSize: number) => {
    fetchData({ current: 1, pageSize, ...formModel.value });
  };
  fetchData();

  // 功能按钮相关
  const importDialogVisible = ref(false);
  const disabled = ref(false);
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const defaultSelected: MemberRecord = {
    username: '',
    name: '',
    email: '',
    phone: '',
    role: '',
    projectAdmin: 0,
    moduleVisible: '0,1',
  };
  const selectForm = ref<MemberRecord>({
    ...defaultSelected,
  });
  const add = () => {
    dialogTitle.value = '添加成员';
    disabled.value = false;
    dialogVisible.value = true;
    selectForm.value = { projectId: projectId.value, ...defaultSelected };
  };
  const update = (record: MemberRecord) => {
    dialogTitle.value = '编辑成员';
    disabled.value = false;
    dialogVisible.value = true;
    selectForm.value = { projectId: projectId.value, ...record };
  };
  const detail = (record: MemberRecord) => {
    dialogTitle.value = '成员详情';
    disabled.value = true;
    dialogVisible.value = true;
    selectForm.value = { projectId: projectId.value, ...record };
  };

  // 生成激活链接并保存到粘贴板
  const { toClipboard } = useClipboard();
  const produceLink = async (id: string) => {
    try {
      const text = `${window.location.origin}/active-user?userid=${id}`;
      await toClipboard(text);
      Message.success('已成功生成激活链接到粘贴板！');
    } catch (err) {
      Message.error('生成激活链接失败');
    }
  };
  const handleSelect = async (value: string, id: string) => {
    try {
      if (value === 'remove') {
        Modal.warning({
          title: '移除成员',
          content: '确认移除该成员?',
          closable: true,
          hideCancel: false,
          onOk: async () => {
            const res = await removeMember(projectId.value, id);
            Message.success('移除成功');
            const { current, pageSize } = pagination;
            fetchData({ pageSize, current, ...formModel.value });
          },
        });
      } else {
        produceLink(id);
      }
    } catch (err) {
      // you can report use errorHandler or other
    }
  };
</script>

<script lang="ts">
  export default {
    name: 'ProjectMember',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 32px 44px 16px;
    height: 100%;
  }
  .table-box {
    height: calc(100% - 128px);
  }
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
  :deep(.arco-btn-size-small) {
    padding: 0 6px;
  }
  :deep(.arco-link:hover) {
    background-color: transparent;
  }
  .action-icon {
    margin-left: 12px;
    cursor: pointer;
  }
  .active {
    color: #0960bd;
    background-color: #e3f4fc;
  }
  .setting {
    display: flex;
    align-items: center;
    width: 200px;
    .title {
      margin-left: 12px;
      cursor: pointer;
    }
  }
  .mini-dot {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
    margin-bottom: 2px;
  }
  .danger-text {
    color: rgb(var(--red-6));
    &:hover {
      color: rgb(var(--red-6));
    }
  }
</style>
